using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages.Communication;
using System.Net;
using System.Web;
using System.IO;

namespace Core
{
	/// <summary>
	/// Summary description for FileUtil.
	/// </summary>
	public class FileUtil
	{
		/// <summary>
		/// Loads the document specified by the URL and returns its content
		/// </summary>
		/// <param name="url">URL to the file</param>
		/// <param name="context">HttpContext (if null, it's not used)</param>
		/// <returns>String containing the content of the specified file.
		/// If the file is part of current SharePoint-site, it's loaded by using the SharePoint objectmodel.
		/// </returns>
		public static string LoadDocument(string url, HttpContext context)
		{
			string content = string.Empty;
			bool fileLoaded = false;

			if (context != null)
			{
				SPWeb thisWeb = SPControl.GetContextWeb(context);
				if (url.ToUpper().IndexOf(thisWeb.Url.ToUpper()) >= 0) // Check if document is part of current site
				{
					try
					{
						content = thisWeb.GetFileAsString(url);
						fileLoaded = true;
					}
					catch (Exception) {}
				}
			}
			if (!fileLoaded)
			{
				WebRequest webReq = WebRequest.Create(url);
				webReq.Credentials = System.Net.CredentialCache.DefaultCredentials;
				WebResponse webResp = webReq.GetResponse();
				using (StreamReader sr = new StreamReader(webResp.GetResponseStream()))
				{
					content = sr.ReadToEnd();
				}
				webResp.Close();
			}
			return content;
		}
	}
}
